package net.freebytes.chat2;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import net.freebytes.chat.MessageTypeEnum;

public class UserRegisterHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        ChannelSessionMemory.deleteWaitingUser(channel.id().toString());
        channel.close();
        ctx.close();
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            String[] messages = ((String) msg).split("&");
            // 消息体有两部分构成  key&value
            // key 用来区分身份，value 是真正的消息
            String key = messages[0];

            Channel channel = ctx.channel();
            if (MessageTypeEnum.USER_REGISTER.getType().equals(key)) {
                // 注册用户
                ChannelSessionMemory.putClientChannel(channel.id().toString(), channel);

                // 用户注册成功后，立刻向用户发送问题列表
                sendInitMessage(channel);
            } else {
                ctx.fireChannelRead(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }


    /**
     * 发送消息
     *
     * @param channel
     */
    private void sendInitMessage(Channel channel) {
        StringBuilder message = new StringBuilder(channel.id().toString() + ",您好，我是智能客服小磕。请告诉你想咨询的服务").append("\r\n")
                .append("1. 死磕 Java 目前哪些系列").append("\r\n")
                .append("2. 死磕 Java 的网址哪个").append("\r\n")
                .append("3. 投诉与建议").append("\r\n")
                .append("0. 人工").append("\r\n")
                .append("==================请输入咨询问题的编号==================");
        String m = MessageTypeEnum.USER_QUESTION.getType() + "&" + message.toString();
        channel.writeAndFlush(m);
    }

}
